package com.unlcn.ils.wms.backend.service.baseData.impl;

import cn.huiyunche.commons.exception.BusinessException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.unlcn.ils.wms.backend.bo.baseDataBO.WmsLocationBO;
import com.unlcn.ils.wms.backend.enums.DeleteFlagEnum;
import com.unlcn.ils.wms.backend.service.baseData.WmsLocationService;
import com.unlcn.ils.wms.backend.util.BitMatrixToImageWritter;
import com.unlcn.ils.wms.backend.util.ObjectToMapUtils;
import com.unlcn.ils.wms.backend.util.jpush.JpushClientUtils;
import com.unlcn.ils.wms.base.businessDTO.baseData.WmsLocationQueryDTO;
import com.unlcn.ils.wms.base.businessDTO.inbound.AsnOrderDTO;
import com.unlcn.ils.wms.base.mapper.additional.WmsLocationExtMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsLocationMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsWarehouseMapper;
import com.unlcn.ils.wms.base.model.stock.WmsLocation;
import com.unlcn.ils.wms.base.model.stock.WmsLocationExample;
import com.unlcn.ils.wms.base.model.stock.WmsWarehouse;
import com.unlcn.ils.wms.base.model.stock.WmsWarehouseExample;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by DELL on 2017/8/18.
 */
@Service
public class WmsLocationServiceImpl implements WmsLocationService {

    private Logger LOGGER = LoggerFactory.getLogger(WmsLocationServiceImpl.class);

    private static final String TYPE_INBOUND = "1002";//入库收货质检和入库确认推送类别

    @Autowired
    private WmsLocationExtMapper wmsLocationExtMapper;

    @Autowired
    private WmsLocationMapper wmsLocationMapper;

    @Override
    public Map<String, Object> listLocation(WmsLocationQueryDTO wmsLocationQueryDTO) throws IllegalAccessException {
        if (Objects.equals(wmsLocationQueryDTO, null)) {
            LOGGER.info("WmsLocationServiceImpl.listLocation must not be null");
            throw new IllegalArgumentException("分页参数不能为空");
        }
        Map<String, Object> resultMap = Maps.newHashMap();

        wmsLocationQueryDTO.setLimitStart(wmsLocationQueryDTO.getStartIndex());
        wmsLocationQueryDTO.setLimitEnd(wmsLocationQueryDTO.getPageSize());

        Map<String, Object> paramMap = ObjectToMapUtils.objectToMap(wmsLocationQueryDTO);
        List<WmsLocation> infos = wmsLocationExtMapper.queryForList(paramMap);
        List<WmsLocationBO> bos = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(infos)) {
            infos.stream().forEach(v -> {
                WmsLocationBO bo = new WmsLocationBO();
                BeanUtils.copyProperties(v, bo);
                bos.add(bo);
            });
            resultMap.put("wmsLocationList", bos);
        }
        wmsLocationQueryDTO.setPageNo(wmsLocationQueryDTO.getStartIndex());
        wmsLocationQueryDTO.setPageSize(wmsLocationQueryDTO.getPageSize());
        wmsLocationQueryDTO.setTotalRecord(wmsLocationExtMapper.queryForCount(paramMap));
        resultMap.put("wmsLocationBO", wmsLocationQueryDTO);
        return resultMap;
    }

    @Autowired
    private WmsWarehouseMapper wmsWarehouseMapper;

    @Override
    public boolean addLocation(WmsLocationBO wmsLocationBO) {

        //重复判断同一库区不能有相同库位

        WmsLocationExample wmsLocationExample = new WmsLocationExample();
        wmsLocationExample.createCriteria().andLocWhCodeEqualTo(wmsLocationBO.getLocWhCode())
                .andLocZoneCodeEqualTo(wmsLocationBO.getLocZoneCode())
                .andLocCodeEqualTo(wmsLocationBO.getLocCode());
        List<WmsLocation> wmsLocationList = wmsLocationMapper.selectByExample(wmsLocationExample);
        if (CollectionUtils.isNotEmpty(wmsLocationList) && wmsLocationList.size() > 0) {
            return false;
        }
        WmsLocation wmsLocation = new WmsLocation();
        BeanUtils.copyProperties(wmsLocationBO, wmsLocation);
        wmsLocation.setIsDeleted((byte) 1);
        wmsLocation.setLocEnableFlag("Y");
        //2018-4-11 设置wms_location的loc_wh_id  维护inbound_allocation关联视图get_location关联关系
        WmsWarehouseExample example = new WmsWarehouseExample();
        example.createCriteria().andWhCodeEqualTo(wmsLocationBO.getLocWhCode())
                .andIsDeletedEqualTo(DeleteFlagEnum.NORMAL.getValue());
        List<WmsWarehouse> wmsWarehouses = wmsWarehouseMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(wmsWarehouses)) {
            WmsWarehouse warehouse = wmsWarehouses.get(0);
            wmsLocation.setLocWhId(String.valueOf(warehouse.getWhId()));
        }
        wmsLocation.setLocName(wmsLocationBO.getLocCode());
        wmsLocationMapper.insert(wmsLocation);
        return true;
    }

    @Override
    public void updateLocation(WmsLocationBO wmsLocationBo) {
        WmsLocation wmsLocation = new WmsLocation();
        BeanUtils.copyProperties(wmsLocationBo, wmsLocation);
        wmsLocationMapper.updateByPrimaryKeySelective(wmsLocation);
    }

    @Override
    public void deleteLocation(List<WmsLocationBO> wmsLocationBOList) {
        wmsLocationBOList.stream().forEach(v -> {
            WmsLocationExample wmsLocationExample = new WmsLocationExample();
            BeanUtils.copyProperties(v, wmsLocationExample);
            wmsLocationMapper.deleteByExample(wmsLocationExample);
        });
    }

    public WmsLocationBO getLocationById(String locId) throws NumberFormatException {
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("locId", locId);
        WmsLocation wmsLocation = wmsLocationMapper.selectByPrimaryKey(Long.valueOf(locId));
        WmsLocationBO wmsLocationBO = new WmsLocationBO();
        BeanUtils.copyProperties(wmsLocation, wmsLocationBO);
        return wmsLocationBO;
    }

    public void enableLocation(List<WmsLocationBO> wmsLocationBOList, String locEnableFlag) {
        List<Long> locIds = Lists.newArrayList();
        wmsLocationBOList.stream().forEach(v -> {
            locIds.add(v.getLocId());
        });
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("locIds", locIds);
        paramMap.put("locEnableFlag", locEnableFlag);
        wmsLocationExtMapper.enableLocation(paramMap);
    }

    /**
     * 推送库位信息给APP
     *
     * @param result 结果
     * @param userId 用户id
     * @throws Exception 异常
     */
    @Override
    public void updateSendToAPPAndPrintCode(AsnOrderDTO result, String userId) throws Exception {
        //推送消息到app
        new Thread(() -> {
            String jsonStr = "{ \"locName\": " + result.getAsnOrderDetailDTOList().get(0).getOddWhLocCode() + ", \"status\":\"20\", \"statusName\": \"已收货待入库\" }";
            //查询移库司机id
            if (StringUtils.isBlank(result.getOdSupplierId())) {
                throw new BusinessException("该车架号:" + result.getAsnOrderDetailDTOList().get(0).getOddVin() + "未绑定移库司机");
            }
            JpushClientUtils.sendToAllAndroid(result.getOdSupplierId(), jsonStr, TYPE_INBOUND);
        }).start();
        //打印二维码
        BufferedImage qrImageBuffer = BitMatrixToImageWritter.createQRImageBuffer(result.getAsnOrderDetailDTOList().get(0).getOddVin(), 60, 60);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(qrImageBuffer, "png", os);
        String base64Img = new Base64().encodeToString(os.toByteArray());
        //BASE64Encoder base64 = new BASE64Encoder();
        //String base64Img = base64.encode(os.toByteArray());
        result.setOdRemark(base64Img);
    }
}
